<template>
  <el-container style="border: solid 1px #5D7DB3; margin: 35px;">
    <el-header style="background-color: #5D7DB3; display: flex; align-items: center; margin-bottom: 20px;">
      <div class="title">
        <span>总队长信箱</span>
      </div>
    </el-header>
    <div>
      <el-main>
        <el-row :gutter="40">
          <el-col :span="4">
            <!-- 添加按钮 -->
            <el-button style="background-color: #5D7DB3; border:none;" class="add" type="success" icon="el-icon-plus"
              @click="showAddDialog">添加</el-button>
          </el-col>
        </el-row>
        <el-table :data="currentCaptainTableData" border stripe 
          @row-click="handleRowClick" :row-class-name="highlightRow">
          <el-table-column prop="name" label="姓名"></el-table-column>
          <el-table-column prop="mail" label="信箱"></el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button type="success" @click="openEditDialog(scope.row)">编辑 <i class="el-icon-edit"></i>
              </el-button>
              <el-button type="danger" @click="handleDelete(scope.row)">删除 <i
                  class="el-icon-remove-outline"></i></el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-main>

      <!-- 添加的弹窗 -->
      <el-dialog title="添加信箱" :visible.sync="addDialogVisible" width="30%" @close="resetForm">
        <el-form :model="form" ref="form" :rules="rules" label-width="100px">
          <el-form-item label="姓名" prop="name">
            <el-input v-model="form.name" placeholder="请输入名称"></el-input>
          </el-form-item>
          <el-form-item label="信箱" prop="mail">
            <el-input v-model="form.mail" placeholder="请输入信箱"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click=" addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </div>
      </el-dialog>
      <!-- 编辑行弹窗 -->
      <el-dialog :visible.sync="editDialogVisible" title="编辑" width="30%">
        <el-form :model="editForm" :rules="rules" label-width="100px">
          <el-form-item label="姓名" prop="name">
            <el-input v-model="editForm.name" placeholder="请输入名称"></el-input>
          </el-form-item>
          <el-form-item label="信箱名称" prop="mail">
            <el-input v-model="editForm.mail" placeholder="请输入信箱名称"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="saveEdit">保存</el-button>
            <el-button @click="editDialogVisible = false">取消</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>
    <el-footer>
      <el-pagination class="CaptainPage" @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="currentPage" :page-sizes="[10, 20, 30, 50]" :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper" :total="captainTableData.length">
      </el-pagination>
    </el-footer>
  </el-container>
</template>

<script>
import axios from 'axios';
export default {
  data() {
    return {
      captainTableData:[],
      currentPage: 1,
      pageSize: 10,
      selectedRow: null,
      addDialogVisible: false,
      editDialogVisible: false,
      editForm: {
        email: '',
      },
      form: {
        name:'',
        email: '',
      },
      rules: {
        name: [
          { required: true, message: '请输入名称', trigger: 'blur' }
        ],
        mail: [
          { required: true, message: '请输入信箱名称', trigger: 'blur' }
        ],
      }
    };
  },
  computed: {
    // 计算当前页的数据
   currentCaptainTableData() {
      const startIndex = (this.currentPage - 1) * this.pageSize;
      const endIndex = startIndex + this.pageSize;
      return this.captainTableData.slice(startIndex, endIndex);
    }
  },
  methods: {
    // 分页大小变化时的回调
    handleSizeChange(val) {
      this.pageSize = val;
    },
    // 当前页变化时的回调
    handleCurrentChange(val) {
      this.currentPage = val;
    },
    //添加邮箱
    showAddDialog() {
      this.addDialogVisible = true;
    },
    resetForm() {
      this.$refs.form.resetFields();
    },
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          const emailAddData = {
            name: this.form.name,
            mail: this.form.mail
          };
          axios.post('/mailbox/add', emailAddData)
            .then(response => {
              console.log('Data successfully sent to backend:', response);
              if (response &&response.status === 200) {
                this.captainTableData.push({
                  name: this.form.name,
                  mail: this.form.mail
                });
                this.$message({
                  type:"success",
                  message:'添加成功'
                });
                this.totalItemNotice = this.captainTableData.length;
                this.currentPageNotice = this.totalPages;
                this.addDialogVisible = false;
                this.$refs.form.resetFields();
              } else {
                console.error('Error sending data to backend:', response);
                this.$message('添加功能出现异常');
              }
            })
            .catch(error => {
              console.error('Error sending data to backend:', error);
              this.$message('添加功能出现异常');
            });
        }
      });
    },
    // 选中变颜色
    handleRowClick(row) {
      this.selectedRow = row; // Update the selected row data
    },
    highlightRow(row) {
      return row === this.selectedRow ? 'highlight' : '';
    },
    // 编辑按钮
    openEditDialog(row) {
      this.editDialogVisible = true;
      this.editForm.name = row.name;
      this.editForm.mail = row.mail;
    },
    saveEdit() {
      const rowIndex = this.captainTableData.indexOf(this.selectedRow);
      this.captainTableData[rowIndex].name = this.editForm.name;
      this.captainTableData[rowIndex].mail = this.editForm.mail;
      // 向后端发送更新请求
      axios.put(`/mailbox/update/${this.selectedRow.mailboxId}`, {
        name: this.editForm.name,
        mail: this.editForm.mail
      })
        .then(() => {
          this.editDialogVisible = false;
          this.$message({
            type: 'success',
            message: '保存成功!'
          });
        })
        .catch(error => {
          console.error('Error updating department:', error);
           this.editDialogVisible = false;
          this.$message.error('保存部门数据时出现错误');
        });
    },
    // 删除按钮
    handleDelete(row) {
      this.$confirm('此操作将删除该部门, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 向后端发送删除请求
        axios.delete(`/mailbox/delete/${row.mailboxId}`)
          .then(() => {
            // 从前端数组中删除部门数据
            const index = this.captainTableData.indexOf(row);
            if (index >= 0 && index < this.captainTableData.length) {
              this.captainTableData.splice(index, 1);
              this.$message({
                type: 'success',
                message: '删除成功!'
              });
            }
          })
          .catch(error => {
            console.error('Error deleting department:', error);
            this.$message.error('删除部门时出现错误');
          });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    }
  },
};
</script>

<style>
.title {
  font-size: 30px;
  font-family: 500;
  color: aliceblue;
}

.highlight {
  background-color: lightblue;
}

.page {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.CaptainPage {
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
